package oss

import (
	"sftti-go-service/types"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/dubbogo/gost/log/logger"
)

var (
	OssClient *oss.Client
)

func InitOss(ossConfig types.OssConfig) {
	var err error
	// 替换为你的阿里云OSS配置
	endpoint := ossConfig.Oss.Endpoint
	accessKeyId := ossConfig.Oss.AccessKey
	accessKeySecret := ossConfig.Oss.AccessSecret
	OssClient, err = oss.New(
		endpoint,
		accessKeyId,
		accessKeySecret,
		oss.AuthVersion(oss.AuthV4),
		oss.Region("cn-shanghai"),
	)
	if err != nil {
		panic(err)
	}
}

func GetObjectToFile(bucketName string, objectKey string, savedFilePath string) error {
	bucket, err := OssClient.Bucket(bucketName)
	if err != nil {
		logger.Errorf("###OSS_Bucket_Err:%s", err)
		return err
	}
	err = bucket.GetObjectToFile(objectKey, savedFilePath)
	if err != nil {
		logger.Errorf("###GetObjectToFile_Err:%s", err)
		return err
	}

	return nil
}

func PutObjectFromFile(bucketName string, objectKey string, toUploadFilePath string) error {
	bucket, err := OssClient.Bucket(bucketName)
	if err != nil {
		logger.Errorf("###OSS_Bucket_Err:%s", err)
		return err
	}
	err = bucket.PutObjectFromFile(objectKey, toUploadFilePath)
	if err != nil {
		logger.Errorf("###PutObjectFromFile_Err:%s", err)
		return err
	}

	return nil
}
